// 登陆注册的接口--后端路由业务逻辑在这里实现
var exp = require('express');
var router = exp.Router();
// 用户规则
var { UserModel } = require('../dbs/users');
// 密令
var { token } = require('../token/index');
// 表示当前路由公共的
router.use(function(req, res, next) {
  next();
});

// 注册
router.post('/register', (req, res) => {
  let { username, password } = req.body;
  // UserModel.deleteOne
  UserModel.create({ username, password })
    .then(doc => {
      res.json({ code: 1, msg: '注册成功' });
    })
    .catch(err => {
      res.json({ code: 0, msg: err.message });
    });
});

// 登陆
router.post('/login', (req, res) => {
  // 先改规则：插入新数据受规则影响，修改不会影响
  // RegisterSchema.remove(['username', 'password', 'rules', 'safes']);
  // const { state, ...sette } = { username: '123', password: "123456", state: 1 }
  // console.log(sette, state);//{username: "123", password: "123456"} 1
  let { state, ...reset } = req.body;
  state = Number(state);
  UserModel.findOneAndUpdate(reset, { loginState: state }, { new: true })
    .lean()
    .then(doc => {
      if (doc) {
        if (state) {
          res.json({
            code: 1,
            data: {
              token: token(doc),
              username: doc.username,
              loginState: doc.loginState,
              rules: doc.rules
            }
          });
        } else {
          // 退出
          res.json({ code: 1, data: { loginState: state }, msg: '退出成功' });
        }
      } else {
        res.json({ code: 0, msg: '没有该用户' });
      }
    })
    .catch(err => {
      res.json({ code: 0, msg: '登陆失败' + err.message });
    });
});

module.exports = router;
